package com.example.summer_pro.controller;

import com.example.summer_pro.entity.Ques;
import com.example.summer_pro.service.QuesService;
import com.example.summer_pro.service.UserService;
import com.example.summer_pro.common.Respond;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/ques")
public class QuesController {
	boolean testWithoutLogin = false;

	@Autowired
	private UserService userService;

	@Autowired
	private QuesService quesService;

	@GetMapping("/getQuesByQid")
	public Map<String, Object> getQuesByQid(
		HttpServletRequest request,
		@RequestParam("qid") Integer qid
	){
		Integer uid =(Integer) request.getSession().getAttribute("u_id");
		if (testWithoutLogin)
			uid = 0;
		Map<String, Object> respond = new HashMap<>();
		respond.put("success", false);
		try{
			Ques ques = quesService.getQuesByQid(qid);
			if (ques == null) {
				respond.put("message", "qid不存在");
				respond.put("data", null);
			} else if (!ques.getU_id().equals(uid)){
				respond.put("message", "没有权限");
				respond.put("data", null);
			} else {
				respond.put("success", true);
				respond.put("message", "OK");
				respond.put("data", ques);
			}
		} catch (Exception e) {
			e.printStackTrace();
			respond.put("success", false);
			respond.put("message", "失败");
		}
		return respond;
	}

	/*
		直接从session中读取uid, 不传参
		应有权限控制 @Auth
	 */
	@GetMapping("/getUserQues")
	public Respond getQuesByUid(
		HttpServletRequest request
	){
		Integer uid =(Integer) request.getSession().getAttribute("u_id");
		if (testWithoutLogin)
			uid = 0;
		Respond respond;
		try{
			if (uid != null) {
				List<Ques> quesList = quesService.getQuesByUid(uid);
				respond = new Respond(true, "OK", quesList);
			} else {
				respond = new Respond(false, "未登录", "");
			}
		} catch (Exception e) {
			e.printStackTrace();
			respond = new Respond(false, "exception", "");
		}
		return respond;
	}

	// 要搜索全部问卷吗 还是只有自己发布的
	// 这里先写 全部搜索了
	@GetMapping("/searchQuesByKeyWord")
	public Respond searchQuesByKeyWord(
		HttpServletRequest request,
		@RequestParam("keyword") String keyWord
	){
		// 这里换了一个写法，这个写法在session无效时不会创建新的session
		Integer uid =(Integer) WebUtils.getSessionAttribute(request, "u_id");
		if (testWithoutLogin)
			uid = 0;
		Respond respond;
		int searchMaxLen = 30; // 关键词最大长度，过长时数据库查询会爆炸
		try {
			if (keyWord.length() <= searchMaxLen) {
				List<Ques> quesList = quesService.getQuesByKeyWord(uid, keyWord);
				respond = new Respond(true, "OK", quesList);
			} else {
				respond = new Respond(false, "关键字太长", "");
			}
		} catch (Exception e) {
			e.printStackTrace();
			respond = new Respond(false, "exception", "");
		}
		return respond;
	}

	@GetMapping("/searchDeleted")
	public Respond searchDeleted(
		HttpServletRequest request,
		@RequestParam("keyword") String keyWord
	){
		// 这里换了一个写法，这个写法在session无效时不会创建新的session
		Integer uid =(Integer) WebUtils.getSessionAttribute(request, "u_id");
		if (testWithoutLogin)
			uid = 0;
		Respond respond;
		int searchMaxLen = 30; // 关键词最大长度，过长时数据库查询会爆炸
		try {
			if (keyWord.length() <= searchMaxLen) {
				List<Ques> quesList = quesService.getDeletedbyKeyWord(uid, keyWord);
				respond = new Respond(true, "OK", quesList);
			} else {
				respond = new Respond(false, "关键字太长", "");
			}
		} catch (Exception e) {
			e.printStackTrace();
			respond = new Respond(false, "exception", "");
		}
		return respond;
	}

	@PostMapping("/copyQues")
	public Respond copyQues(
		HttpServletRequest request,
		// map: {"qid": qid}
		@RequestBody Map<String, Integer> remap
	){
		Integer uid = (Integer) WebUtils.getSessionAttribute(request, "u_id");
		Integer qid = remap.get("qid");
		if (testWithoutLogin)
			uid = 0;
		Respond respond;
		if (qid == null){
			respond = new Respond(false, "缺少参数qid", "");
		} else {
			try {
				int new_qid = quesService.copyQues(uid, qid);
				Ques new_ques = quesService.getQuesByQid(new_qid);
				respond = new Respond(true, "OK", new_ques);
			} catch (Exception e) {
				e.printStackTrace();
				respond = new Respond(false, "exception", "");
			}
		}
		return respond;
	}


	// 需要权限控制
	@PostMapping("/delQues")
	public Respond delQues(
		HttpServletRequest request,
		@RequestBody Map<String, Integer> remap
	){
		Integer uid = (Integer) WebUtils.getSessionAttribute(request, "u_id");
		Integer qid = remap.get("qid");
		if (testWithoutLogin)
			uid = 0;
		Respond respond;
		if (qid == null){
			respond = new Respond(false, "缺少参数qid", "");
		} else {
			try {
				int status = quesService.delQues(uid, qid);
				respond = checkReturnStatus(status);
			} catch (Exception e) {
				e.printStackTrace();
				respond = new Respond(false, "exception: " + e.getMessage(), "");
			}
		}
		return respond;
	}

	@GetMapping("/getUserDeleted")
	public Respond getUserDeleted(
		HttpServletRequest request
	){
		Integer uid = (Integer) WebUtils.getSessionAttribute(request, "u_id");
		if (testWithoutLogin)
			uid = 0;
		Respond respond;
		try {
			if (uid != null)
				respond = new Respond(true, "OK", quesService.getDeletedbyUid(uid));
			else
				respond = new Respond(false, "未登录", "");
		} catch (Exception e) {
			e.printStackTrace();
			respond = new Respond(false, "exception", "");
		}
		return respond;
	}

	@PostMapping("/createQues")
	public Respond createQues(
		HttpServletRequest request,
		// todo: 遇到了一点问题，这里不同的问卷怎么共用一个list<问卷类型>
		@RequestBody @Valid Ques ques
	){
		Integer uid = (Integer) WebUtils.getSessionAttribute(request, "u_id");
		if (testWithoutLogin)
			uid = 0;
		Respond respond = new Respond(false, "error", "");

		if (uid == null) {
			respond = new Respond(false, "未登录", "");
		} else {
			try {
				int qid = quesService.createQues(uid, ques);
				respond = new Respond(true, "OK", qid);
			} catch (Exception e) {
				e.printStackTrace();
				respond = new Respond(false, "exception", "");
			}
		}

		return respond;
	}

	@PostMapping("/unDelete")
	public Respond unDelete(
		HttpServletRequest request,
		// map: {"qid": qid}
		@RequestBody Map<String, Integer> map
	){
		Integer uid = (Integer) WebUtils.getSessionAttribute(request, "u_id");
		if (testWithoutLogin)
			uid = 0;
		Integer qid = map.get("qid");
		Respond respond = new Respond(false, "error", "");

		if (uid == null) {
			respond = new Respond(false, "未登录", "");
		} else {
			try {
				int status = quesService.unDeleteQues(uid, qid);
				respond = checkReturnStatus(status);

			} catch (Exception e) {
				e.printStackTrace();
				respond = new Respond(false, "exception", "");
			}
		}
		return respond;
	}

	// todo: 甚至单数据修改的controoler层 结构都是一样的
	// 能做到自动处理吗
	@PostMapping("/setState")
	public Respond setState(
		HttpServletRequest request,
		// map: {"qid": (int)qid, "state": (int)state}
		@RequestBody Map<String, Integer> map
	){
		Integer uid = (Integer) WebUtils.getSessionAttribute(request, "u_id");
		if (testWithoutLogin)
			uid = 0;
		Integer qid = map.get("qid");
		Integer state = map.get("state");
		Respond respond;

		if (uid == null) {
			respond = new Respond(false, "未登录", "");
		} else {
			try {
				int status = quesService.setState(uid, qid, state);
				respond = checkReturnStatus(status);

			} catch (Exception e) {
				System.out.printf("/setState {qid: %d, state: %d}\n", qid, state);
				e.printStackTrace();
				respond = new Respond(false, "exception", "");
			}
		}
		return respond;
	}

	@PostMapping("/setValidTime")
	public Respond setValidTime(
		HttpServletRequest request,
		// map: {"qid": (int), "valid_time": (Date)}
		@RequestBody Map<String, String> map
	){
		Integer uid = (Integer) WebUtils.getSessionAttribute(request, "u_id");
		if (testWithoutLogin)
			uid = 0;
		Integer qid = Integer.parseInt(map.get("qid"));
		SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd hh:mm:ss");
		Date date;
		try {
			date = sdf.parse(map.get("valid_time"));
		} catch (Exception e) {
			System.out.println(map.get("valid_time"));
			e.printStackTrace();
			return new Respond(false, "时间格式非法");
		}
		Respond respond;

		if (uid == null) {
			respond = new Respond(false, "未登录", "");
		} else {
			try {
				int status = quesService.setValidTime(uid, qid, date);
				respond = checkReturnStatus(status);
			} catch (Exception e) {
				e.printStackTrace();
				respond = new Respond(false, "exception", "");
			}
		}
		return respond;
	}


	// todo: 所有问卷操作的部分 都需要权限控制
	// 需要注册注解 先这么写着
	private Respond checkReturnStatus(Integer status) {
		switch (status) {
			case 0:
				return new Respond(true, "OK", "");
			case 1:
				return new Respond(false, "问卷不存在", "");
			case 2:
				return new Respond(false, "问卷不属于该用户", "");
			default:
				return new Respond(false, "失败", "");
		}
	}
}